<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="调拨状态" prop="dbZt">
        <el-select size="mini" v-model="queryParams.dbZt" placeholder="请选择调拨状态" clearable>
          <el-option
            v-for="dict in dict.type.sbdb_dbzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调拨日期">
        <el-date-picker size="mini"
                        v-model="daterangeCkRq"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="调拨人" prop="ckName">
        <el-input size="mini"
                  v-model="queryParams.ckName"
                  placeholder="请输入出库人"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sbgl:sbdb:add']"
        >新增设备调拨单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="!selectedRow || (selectedRow.dbZt !== '待调拨')"
          @click="handleUpdate"
          v-hasPermi="['sbgl:sbdb:edit']"
        >修改设备调拨单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="!selectedRow || (selectedRow.dbZt !== '待调拨')"
          @click="handleDelete"
          v-hasPermi="['sbgl:sbdb:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sbgl:sbdb:export']"
        >导出Excel
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini"-->
<!--          @click="handleImport"-->
<!--          v-hasPermi="['sbgl:sbdb:import']"-->
<!--        >导入-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-delete"
        :disabled="single"
        @click="handleExports"
      >导出docx</el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="sbdbList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="调拨状态" align="center" prop="dbZt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sbdb_dbzt" :value="scope.row.dbZt"/>
        </template>
      </el-table-column>
      <el-table-column label="调拨日期" align="center" prop="ckRq" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ckRq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨人" align="center" prop="ckName"/>
      <el-table-column label="调拨详情" align="center" >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleButtonClick(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-link style="color: #44d744; font-weight: 600" type="danger" disabled v-if="scope.row.dbZt == '调拨完成'">{{'已调拨完成'}}</el-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="qdDb(scope.row)"
            v-if="scope.row.dbZt == '待调拨'"
          >待调拨/确定调拨
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.dbZt == '待调拨'"
            v-hasPermi="['sbgl:sbdb:edit']"
          >修改
          </el-button>
<!--          v-if="scope.row.dbZt == '待调拨'"-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.dbZt == '待调拨'"
            v-hasPermi="['sbgl:sbdb:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-containers" v-show="total > 0">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 导入对话框 -->
    <vxe-modal :title="upload.title" v-model="upload.open" width="400px" showFooter show-zoom resize>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 添加或修改设备调拨对话框 -->
    <vxe-modal :title="title" v-model="open" width="70%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="80px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">调拨基本信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="出库日期" prop="ckRq">
                <el-date-picker clearable style="width: 100%;"
                                v-model="form.ckRq"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择出库日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出库人" prop="ckName">
                <el-input v-model="form.ckName" placeholder="请输入出库人"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix" style="text-align: center;">
              <span style="font-size: 20px; color: #1890ff">设备调拨明细</span>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSbdbDbmx">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSbdbDbmx">删除
                </el-button>
              </el-col>
            </el-row>
            <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                      height="45vh" :data="sbdbDbmxList" :row-class-name="rowSbdbDbmxIndex"
                      @selection-change="handleSbdbDbmxSelectionChange" ref="sbdbDbmx">
              <el-table-column type="selection" width="50" align="center" show-overflow-tooltip/>
              <el-table-column label="序号" align="center" prop="index" width="50" show-overflow-tooltip/>
              <el-table-column v-if="1 === 2" label="设备ID" prop="sbxxglId" show-overflow-tooltip/>
              <el-table-column label="设备名称" align="center" prop="sbName" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="handleSbXqClick(scope.row)"
                  >
                    <el-link style="font-weight: 600" type="primary">{{ scope.row.sbName }}</el-link>
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" prop="dw" show-overflow-tooltip/>
              <el-table-column label="规格型号" align="center" prop="ggXh" show-overflow-tooltip/>
              <el-table-column label="领用项目" align="center" prop="lyXm" show-overflow-tooltip>
                <template slot-scope="scope">
                  <!--              <el-input v-model="scope.row.lyXm" placeholder="请输入领用项目" />-->
                  <el-select filterable v-model="scope.row.lyXm" placeholder="选择领用项目" style="width: 100%">
                    <el-option
                      v-for="item in lyXmList"
                      :key="item.xmxxglId"
                      :label="item.xmName"
                      :value="item.xmName">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="出厂编号" align="center" prop="ccBh" show-overflow-tooltip/>
              <el-table-column label="自编号" align="center" prop="zbh" show-overflow-tooltip/>
              <el-table-column label="固定资产编号" align="center" prop="gdZcBh" show-overflow-tooltip/>
              <el-table-column label="备注" align="center" prop="bz" width="150" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-input v-model="scope.row.bz" placeholder="请输入备注"/>
                </template>
              </el-table-column>
            </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 设备多选组件 -->
    <SbDuoX ref="sbDuoX"/>

    <!-- 设备调拨详情 -->
    <SbDbXq ref="sbDbXq"/>

    <!-- 设备详情 -->
    <SbXq ref="sbXq"/>
  </div>
</template>

<script>
import {addSbdb, delSbdb, exportSbDbWord, getSbdb, listSbdb, updateSbdb} from "@/api/sbgl/sbdb";
import {getToken} from "@/utils/auth";
import SbDuoX from "@/views/components/sbDuoX/index.vue";
import {selectXmList} from "@/api/sbgl/xmxxgl";
import {getSbxxgl, updateSbxxgl} from "@/api/sbgl/sbxxgl";
import SbDbXq from "@/views/sbgl/sbdb/components/SbDbXq.vue";
import SbXq from "@/views/sbgl/sbxxgl/components/SbXq.vue";

export default {
  name: "Sbdb",
  components: {SbXq, SbDbXq, SbDuoX},
  dicts: ['sbdb_dbzt'],
  provide() {
    return {
      updateSbLabel: (val) => {
        val.forEach(item => {
          // 检查是否已存在相同的 出厂编号
          const exists = this.sbdbDbmxList.some(existingItem => existingItem.sbxxglId === item.sbxxglId);
          if (!exists) {
            this.sbdbDbmxList.push(item);
          }
        })
      },
    };
  },
  data() {
    return {
      lyXmList: [], //所在项目(项目列表)
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSbdbDbmx: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备调拨表格数据
      sbdbList: [],
      // 设备调拨明细表格数据
      sbdbDbmxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 设备ID时间范围
      daterangeCkRq: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbZt: null,
        ckRq: null,
        ckName: null,
        userId: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ckRq: [{required: true, message: "出库日期不能为空", trigger: "blur"}],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sbgl/sbdb/importData"
      }
    };
  },
  created() {
    this.getList();
    this.selectLyXm();
  },
  methods: {
    // 查询设备详情信息
    handleSbXqClick(row) {
      this.$refs.sbXq.handleOpen(row);
    },
    //导出word按钮操作
    handleExports() {
      const row = this.selectedRow; // 获取当前选中的行
      console.log(row, 'asdasdasd')
      const queryParams = this.queryParams;
      const sbdbId = row.sbdbId;
      this.$confirm('是否确认导出word文档?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true
        return exportSbDbWord(queryParams, sbdbId); // Passing userId to the exportWord function
      }).then(response => {
        // console.log('/profile/upload/' + response.msg)
        this.$download.resource('/profile/upload/' + response.msg);
        this.loading = false
      }).catch(() => {});
    },
    // 查询设备调拨详情
    handleButtonClick(row) {
      this.$refs.sbDbXq.handleOpen(row)
    },
    //确定调拨
    qdDb(row) {
      this.reset();
      const sbdbId = row.sbdbId

      this.$confirm('是否确认调拨? 调拨完成后将无法再次修改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$modal.loading("正在完成调拨中，请稍后...");
        getSbdb(sbdbId).then(res => {
          const sbDbMxList = res.data.sbdbDbmxList
          this.sbdbDbmxList = res.data.sbdbDbmxList;
          for (let i = 0; i < sbDbMxList.length; i++) {
            let item = sbDbMxList[i]
            // 删除 sbdbId 属性
            delete item.sbdbId;
            this.sbForm = {
              sbxxglId: item.sbxxglId, idWhere: null, sbName: null, ccBh: null, zbh: null, gdZcBh: null, jzZq: null,
              ggXh: null, zqdBzqd: null, szXm: item.lyXm, dw: null, scCj: null, sbLx: null, clFw: null, yxqZ: null, gzRq: null,
              sbBz: null, createBy: null, createTime: null, updateBy: null, updateTime: null, userId: null, deptId: null
            };
            updateSbxxgl(this.sbForm).then(response => {
            });
          }
          this.form.dbZt = '调拨完成'
          // 关闭遮罩层
          this.form.sbdbId = sbdbId
          this.form.sbdbDbmxList = this.sbdbDbmxList;
          updateSbdb(this.form).then(response => {
            this.$modal.msgSuccess("调拨完成! 设备已调拨到相应的领用项目");
            this.$modal.closeLoading();
            this.getList();
          });

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //领用项目列表
    selectLyXm() {
      //不分页查询项目列表
      selectXmList().then(res => {
        this.lyXmList = res.data
      })
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询设备调拨列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCkRq && '' != this.daterangeCkRq) {
        this.queryParams.params["beginCkRq"] = this.daterangeCkRq[0];
        this.queryParams.params["endCkRq"] = this.daterangeCkRq[1];
      }
      listSbdb(this.queryParams).then(response => {
        this.sbdbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sbdbId: null,
        dbZt: null,
        ckRq: null,
        ckName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.sbdbDbmxList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCkRq = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sbdbId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备调拨";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sbdbId = row.sbdbId || this.ids
      getSbdb(sbdbId).then(response => {
        this.form = response.data;
        this.sbdbDbmxList = response.data.sbdbDbmxList;
        this.open = true;
        this.title = "修改设备调拨";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.sbdbDbmxList = this.sbdbDbmxList;

          if (this.form.sbdbDbmxList.length == 0) {
            this.$modal.msgError("设备调拨明细不能为空");
            return
          }
          for (let i = 0; i < this.form.sbdbDbmxList.length; i++) {
            let item = this.form.sbdbDbmxList[i]
            if (item.lyXm == null) {
              this.$modal.msgError("第" + (i + 1) + "行，领用项目为空，请检查");
              return
            }
          }

          if (this.form.sbdbId != null) {
            updateSbdb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSbdb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sbdbIds = row.sbdbId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delSbdb(sbdbIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 设备调拨明细序号 */
    rowSbdbDbmxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 设备调拨明细添加按钮操作 */
    handleAddSbdbDbmx() {
      this.$refs.sbDuoX.handleOpen(this.sbdbDbmxList)
      // let obj = {};
      // obj.sbxxglId = "";
      // obj.sbName = "";
      // obj.dw = "";
      // obj.ggXh = "";
      // obj.lyXm = "";
      // obj.ccBh = "";
      // obj.zbh = "";
      // obj.gdZcBh = "";
      // obj.bz = "";
      // this.sbdbDbmxList.push(obj);
    },
    /** 设备调拨明细删除按钮操作 */
    handleDeleteSbdbDbmx() {
      if (this.checkedSbdbDbmx.length == 0) {
        this.$modal.msgError("请先选择要删除的设备调拨明细数据");
      } else {
        const sbdbDbmxList = this.sbdbDbmxList;
        const checkedSbdbDbmx = this.checkedSbdbDbmx;
        this.sbdbDbmxList = sbdbDbmxList.filter(function (item) {
          return checkedSbdbDbmx.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSbdbDbmxSelectionChange(selection) {
      this.checkedSbdbDbmx = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sbgl/sbdb/export', {
        ...this.queryParams
      }, `sbdb_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('sbgl/sbdb/importTemplate', {}, `template_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备调拨导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
